package com.vivimice.lotroller.device;

import java.util.HashMap;
import java.util.Map;

import com.vivimice.lotroller.notification.NotificationAgent;
import com.vivimice.lotroller.notification.NotificationListener;
import com.vivimice.lotroller.notification.NotificationType;

/**
 * A device which listens at the specified type of notification, then triggers
 * the next device (if exists).
 * 
 * If positiveType is notified, the device's status is true. If negativeType is
 * is notified, the device's status is false.
 * 
 * The data along with the notification can be retrived through getDataMap method
 * 
 * @author vivimice
 *
 */
public class InputDevice extends Device {

	private NotificationAgent agent;
	private NotificationType positiveType;
	private NotificationType negativeType;
	private Map<NotificationType, Object> dataMap = new HashMap<NotificationType, Object>();;
	private boolean status;
	
	private NotificationListener listener = new NotificationListener() {
		@Override
		public void onNotify(NotificationType type, Object data) {
			status = (type == positiveType);
			dataMap.put(type, data);
			trigger();
		}
	};
	
	public InputDevice(NotificationAgent agent, NotificationType positiveType, NotificationType negativeType) {
		this.status = false;
		this.agent = agent;
		this.positiveType = positiveType;
		this.negativeType = negativeType;
		
		if (positiveType != null) {
			agent.addListener(positiveType, listener);
		}
		
		if (negativeType != null) {
			agent.addListener(negativeType, listener);
		}
	}
	
	public InputDevice(NotificationAgent agent, NotificationType positiveType) {
		this(agent, positiveType, null);
	}
	
	@Override
	public boolean getStatus() {
		return status;
	}

	@Override
	public Map<NotificationType, Object> getDataMap() {
		return dataMap;
	}

	@Override
	public void close() {
		if (positiveType != null) {
			agent.removeListener(positiveType, listener);
		}
		
		if (negativeType != null) {
			agent.removeListener(negativeType, listener);
		}
	}
	
}
